<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="大屏名称" prop="largeScreenName">
        <el-input v-model="queryParams.largeScreenName" placeholder="请输入大屏名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['datascreen:largeScreen:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['datascreen:largeScreen:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['datascreen:largeScreen:remove']">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="largeScreenList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="largeScreenId" v-if="true" />
      <el-table-column label="大屏名称" align="center" prop="largeScreenName" />
      <!-- <el-table-column label="页面内容" align="center" prop="content" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleDesign(scope.row)"
            v-hasPermi="['datascreen:largeScreen:edit']">设计</el-button>
          <el-button link type="primary" icon="Edit" @click="handlePreview(scope.row)"
            v-hasPermi="['datascreen:largeScreen:query']">预览</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['datascreen:largeScreen:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['datascreen:largeScreen:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改大屏信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="largeScreenRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="大屏名称" prop="largeScreenName">
          <el-input v-model="form.largeScreenName" placeholder="请输入大屏名称" />
        </el-form-item>
        <!-- <el-form-item label="页面内容" prop="content">
          <el-input v-model="form.content" placeholder="请输入页面内容" />
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设计弹框 -->
    <el-dialog :title="title" v-model="openDesign" width="500px" :fullscreen="true" destroy-on-close append-to-body>
      <el-tabs v-model="designActiveName" @tab-click="designHandleClick">
        <el-tab-pane label="Vue" name="vue">
          <div style="display: flex;">
            <code-editor ref="codeEditorVue" :mode="'html'" width="calc(100vw - 300px)" height="500px" v-model="form.content"
              :user-worker="false"></code-editor>
            <div style="width: 300px; text-align: right;">
              <el-select v-model="elementId" placeholder="请选择">
                <el-option
                  v-for="item in elementList"
                  :key="item.elementId"
                  :label="item.elementName"
                  :value="item.elementId"
                />
              </el-select>
              <br/>
              <br/>
              <el-button :loading="buttonLoading" type="success" @click="insertElement">插入</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="预览" name="view">
          <div style="width: 100%; min-height: 500px">
            <LargeScreenComponents v-show="form.content" :content="form.content" :key="largeScreenComponentsKey" />
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="saveDesign">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LargeScreen">
import { listLargeScreen, getLargeScreen, delLargeScreen, addLargeScreen, updateLargeScreen } from "@/api/datascreen/largeScreen";
import CodeEditor from '@/components/code-editor/index'
import LargeScreenComponents from '@/components/LargeScreen/index.vue'
import { listAllElement } from "@/api/datascreen/element";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict('sys_normal_disable');

const largeScreenList = ref([]);
const open = ref(false);
const openDesign = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const designActiveName = ref('vue')
const largeScreenComponentsKey = ref(0)
const elementList = ref([])
const elementId = ref(null)
const codeEditorVue = ref(null)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    largeScreenName: undefined,
    content: undefined,
    status: undefined,
  },
  rules: {
    largeScreenId: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    largeScreenName: [
      { required: true, message: "大屏名称不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询大屏信息列表 */
function getList() {
  loading.value = true;
  listLargeScreen(queryParams.value).then(response => {
    largeScreenList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询大屏元素列表 */
function getlistAllElement() {
  listAllElement({ status: '0' }).then(response => {
    elementList.value = response.data
  })
}

// 取消按钮
function cancel() {
  open.value = false;
  openDesign.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    largeScreenId: null,
    largeScreenName: null,
    content: null,
    status: '0',
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("largeScreenRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.largeScreenId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加大屏信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _largeScreenId = row.largeScreenId || ids.value
  getLargeScreen(_largeScreenId).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改大屏信息";
  });
}

/** 设计按钮操作 */
function handleDesign(row) {
  loading.value = true
  getLargeScreen(row.largeScreenId).then(response => {
    loading.value = false;
    form.value = response.data;
    title.value = row.largeScreenName + '大屏设计'
    openDesign.value = true
  });
}

/** tabs切换操作 */
function designHandleClick(tab, event) {
  if ('vue' == designActiveName.value) {
    largeScreenComponentsKey.value++
  }
}

/** 插入元素操作 */
function insertElement(){
  codeEditorVue.value.insertValue('<DatascreenElement elementId="' + elementId.value + '" />')
}

/** 预览按钮操作 */
function handlePreview(row) {
  window.open("http://localhost/datascreen/" + row.largeScreenId)
}

/** 设计保存 */
function saveDesign() {
  buttonLoading.value = true;
  if (form.value.largeScreenId != null && form.value.content) {
    updateLargeScreen(form.value).then(response => {
      proxy.$modal.msgSuccess("修改成功");
      openDesign.value = false;
      getList();
    }).finally(() => {
      buttonLoading.value = false;
    });
    return;
  }

  proxy.$modal.msgError("数据不合法");
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["largeScreenRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.largeScreenId != null) {
        updateLargeScreen(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addLargeScreen(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _largeScreenIds = row.largeScreenId || ids.value;
  proxy.$modal.confirm('是否确认删除大屏信息编号为"' + _largeScreenIds + '"的数据项？').then(function () {
    loading.value = true;
    return delLargeScreen(_largeScreenIds);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
// function handleExport() {
//   proxy.download('datascreen/largeScreen/export', {
//     ...queryParams.value
//   }, `largeScreen_${new Date().getTime()}.xlsx`)
// }

getlistAllElement();
getList();
</script>
